<template>
  <div>
    <span class="_before">订单分配</span>
    <el-row>
      <el-col :offset="3" :span="2" style="text-align: center;">经办人</el-col>
      <el-col :span="24"></el-col>
      <el-col :offset="3" :span="2" style="border-top: 1px solid #aaa;margin-top: 5px;">
        <el-select v-model="userInfo.handleUser" :disabled="props.handledBy" style="padding-top: 5px;">
          <el-option v-for="(item,index) in userInfo.handleUserList" :key="index" :label="item.handleUserName" :value="item.handleUserId" />
        </el-select>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-row style="margin: 20px 0;">
          <el-col :offset="3" :span="2" class="alignCenter">业务员</el-col>
          <el-col :offset="4" :span="2">操作员</el-col>
          <el-col :offset="4" :span="6">业务编号</el-col>
        </el-row>
        <template v-for="(item, index) in (getAllocation ? getAllocation : param.allocation)" :key="index">
          <el-row style="margin-top: 10px;">
            <el-col :offset="3" :span="3">
                <el-select v-model="item.businessUser" style="width:150px" placeholder="请选择业务员" :disabled="disabled">
                  <el-option v-for="(business,index) in props.userSimpleList" :key="index" :label="business.userName"
                    :value="business.userId" />
                </el-select>
            </el-col>
            <el-col :offset="1" :span="5" style="text-align: center;">
              <el-select v-model="item.operateUsers" style="width:150px" multiple collapse-tags placeholder="请选择操作员" :disabled="disabled">
                <el-option v-for="(operate,index) in props.userSimpleList" :key="index" :label="operate.userName"
                    :value="operate.userId" />
              </el-select>
            </el-col>
            <el-col :offset="2" :span="3" style="text-align: center;">
              <el-input v-model="item.businessNo" style="width:100%;" placeholder="请输入业务编号" :disabled="disabled"></el-input>
            </el-col>
            <el-col :span="2" style="margin: auto 0;">
              <el-row>
                <el-col :offset="1" :span="6" v-if="param.allocation.length > 1">
                  <el-button @click="handleDelete(index)" icon="Delete" type="danger" size="small" circle plain></el-button>
                </el-col>
                <el-col :span="8" v-if="index == param.allocation.length - 1">
                  <el-button @click="handleAdd" icon="Plus" type="info" size="small" circle plain></el-button>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-col>
    </el-row>
  </div>

</template>

<script setup lang="ts">
import { FormInstance, ElMessage} from 'element-plus';
import Cookies from "js-cookie";
import { ref, reactive, onMounted,computed, watch, onActivated, onDeactivated } from 'vue'

const ruleFormRef1 = ref()
const ruleFormRef = ref([])

const props = defineProps({
  rowData: {
    type: Object,
    default: () => { }
  },
  disabled: {
    type: Boolean,
    default: false
  },
  displayType:{
    type: String,
    default:''
  },
  allocation:{
    required: true,
    type:Array
  },
  allocation1:{
    required: true,
    type:Array
  },
  userSimpleList:{
    required: true,
    type:Array
  },
  citingSources:{ //组件引用来源 hdzx：货代 租箱下单页面
    type: String,
    default:''
  },
  handledBy:{
    type: Boolean,
    default: false
  }
})

const param = reactive({
  businessUserList: [{ "businessUserId": 4, "businessUserName": "李四" }, { "businessUserId": 6, "businessUserName": "赵六" }],
  operateUserList: [{ "operateUserId": 3, "operateUserName": "张三" }, { "operateUserId": 5, "operateUserName": "王五" }],
  userList:[],//操作员和业务员为的数据相同
  allocation: [{businessUser: '', operateUsers: [], businessNo: ''}]
  // allocation: []
})

const userInfo = reactive({
  handleUser:'',
  handleUserList:[{"handleUserId":"","handleUserName":""}]
})
onActivated(() => {
  userInfo.handleUser = JSON.parse(Cookies.get("User-Info"))?.nickname
  userInfo.handleUserList[0].handleUserId = JSON.parse(Cookies.get("User-Info"))?.id
  userInfo.handleUserList[0].handleUserName = JSON.parse(Cookies.get("User-Info"))?.nickname
})
// 获取经办人  业务员  操作员等信息 
watch([props.rowData],([newVal1], [oldVal1]) =>{
    // val1 属性一处理
    let allocation = []
    try {
        allocation = JSON.parse(newVal1.allocation)
    } catch (e) {
        try {
          allocation = JSON.parse(oldVal1.allocation)
        }catch (e) {
          console.log('字符串解析错误')
        }
    }
    
    if (allocation) {
      if (!Array.isArray(allocation)) {
        allocation = JSON.parse(allocation)
      }
      allocation.forEach(item => {
        item.businessUser = item.businessUserId
        item.operateUsers = item.operateUser.map(item => item.operateUserId)
      })
      param.allocation =  allocation.length > 0 ? allocation : param.allocation
      // userInfo.handleUser = allocation[0]?.handleUserId
    }
},{ immediate: true,deep: true })

onDeactivated(() => {
  ruleFormRef.value.forEach((item) => {
    resetForm(item)
  })
  resetForm(ruleFormRef1.value)
 
})
const getAllocation = computed(() => {
  let allocation = []
  if(props.rowData?.allocation){
     allocation = props.rowData.allocation
    if (!Array.isArray(allocation)) {
      allocation = JSON.parse(allocation)
    }
    allocation.forEach(item => {
      item.businessUser = item.businessUserId
      item.operateUsers = item.operateUser.map(item => item.operateUserId)
    })
    // allocation =  allocation.length > 0 ? allocation : param.allocation
    return  allocation
  }else{
    // let baseInfo = {businessUser: '', operateUsers: [], businessNo: ''}
    // allocation.push(baseInfo)
    return false
  }
  
})

const rules = reactive({
  businessUser: [
    { required: true, message: '必填项', trigger: 'change' }
  ],
  businessNo: [
    { required: true, message: '必填项', trigger: 'blur' }
  ],
  operateUsers: [
    { required: true, message: '必填项', trigger: 'change' }
  ],
})

const rulesHandleUser = reactive({
  handleUser: [
    { required: true, message: '必填项', trigger: 'change' }
  ],
})

//
const handleAdd = () => {
  console.log('handleAdd')
  const data = param.allocation[param.allocation.length - 1] //新增 默认copy最后一行的数据
  const allocation = JSON.parse(JSON.stringify(data))
  param.allocation.push(allocation)
}
const handleDelete = (index: any) => {
  console.log('handleDelete')
  param.allocation.splice(index, 1)
}
const handleChange = () => {
  param.allocation.handleUser = userInfo.handleUser
}


/*
* @param 查询 list 中 key字段 内容等于 val 的 object 的 name 
* @return return 符合条件的name
*/
const allocationNameFilter = (list: any, key: string, val: any, name: string) => {
  if (list.length == 0) return ''

  const result = list.find((item: any) => {
    return item[key] == val
  })
  if (result == undefined) return ''
  // console.log(result)
  return result[name]
}

const getAllocationTemplate = () => {
  let arry: any = []
  param.allocation.forEach((el) => {
    if (el.operateUsers.length < 1) return 
    const operateUser = el.operateUsers.map(id => ({
      operateUserId: id,
      // operateUserName: allocationNameFilter(param.operateUserList, 'operateUserId', id, 'operateUserName')
      
      operateUserName: allocationNameFilter(props.userSimpleList, 'userId', id, 'userName')
    }));
    arry.push({
      "operateUser": operateUser,
      "businessUserId": el.businessUser,
      "businessUserName": allocationNameFilter(props.userSimpleList, 'userId', el.businessUser, 'userName'),
      "handleUserId":allocationNameFilter(userInfo.handleUserList, 'handleUserName', userInfo.handleUser, 'handleUserId') , //经办人
      "handleUserName": userInfo.handleUser,
      "businessNo": el.businessNo
    })
  })
  return arry
}

const onSubmit = async () => {
  let resut1 = userInfo.handleUser.length > 0 ? true : false

  if(resut1){
    return true
  }else{
    return false
  }
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

defineExpose({
  allocation: param.allocation,
  onSubmit: onSubmit,
  getAllocationTemplate
})

</script>
<style scoped>
.alignCenter{
  text-align: center;
}
</style>